function patch(oldNode,vnode,vm){
  const isRealElement = oldNode.nodeType;
  let el = createElement(vnode,vm);
  let parentElement = oldNode.parentNode;
  parentElement.insertBefore(el,oldNode.nextSibling);
  parentElement.removeChild(oldNode)
}
function createElement(vnode,vm){

  const {tag,props,children,text} =vnode;
  if(typeof tag ==='string'){
    vnode.el = document.createElement(tag);
    if(vnode.props.on){
      
      // directive(vnode,vm);
      updateON(vnode,vm);
    }
    updateProps(vnode);
    children.map(child =>{
      vnode.el.appendChild(createElement(child,vm));
    })
  }else {
    vnode.el = document.createTextNode(text);
  }
  return vnode.el;
}
function updateProps(vnode){
  const el = vnode.el;
  const newProps = vnode.props || {};

  for (let key in newProps) {
    if(key ==='style'){
      for(let sKey in newProps.style){
        el.style[sKey] = newProps.style[sKey]
      }
    }else if (key ==='class'){
      el.className = newProps[key];
    }else {
      el.setAttribute(key,newProps[key])
    }
    
  }
}
function updateON(vnode,vm){
  var [key,value] = Object.keys(vnode.props.on)
  const fn = vnode.props.on[key]
  if(key==='click'){
    
    vnode.el.addEventListener(`click`,()=>{
      fn.call(vm)
    })
  }else if(key==='input'){
    vnode.el.addEventListener(`input`,($event)=>{
      fn.call(vm,$event)
    })
  }
  
}
function directive(vnode,vm){
  vnode.el.addEventListener('input',(newValue)=>{
    console.log(vm)
    vm[vnode.props.directives[0].expression] = newValue;
  })
}
export {patch}